// 迷宫的行数和列数
const ROWS = 10;
const COLS = 10;

// 获取迷宫容器
const mazeContainer = document.getElementById('maze-container');

// 迷宫二维数组
let maze = [];

// 玩家位置
let playerRow = 0;
let playerCol = 0;

// 出口位置
let exitRow = ROWS - 1;
let exitCol = COLS - 1;

// 初始化迷宫
function initMaze() {
    for (let i = 0; i < ROWS; i++) {
        maze[i] = [];
        for (let j = 0; j < COLS; j++) {
            if (Math.random() < 0.3) {
                maze[i][j] = 1; // 墙
            } else {
                maze[i][j] = 0; // 通路
            }
        }
    }
    // 确保起点和终点是通路
    maze[playerRow][playerCol] = 0;
    maze[exitRow][exitCol] = 0;
}

// 绘制迷宫
function drawMaze() {
    mazeContainer.innerHTML = '';
    for (let i = 0; i < ROWS; i++) {
        for (let j = 0; j < COLS; j++) {
            const cell = document.createElement('div');
            cell.classList.add('cell');
            if (maze[i][j] === 1) {
                cell.classList.add('wall');
            } else if (i === playerRow && j === playerCol) {
                cell.classList.add('player');
            } else if (i === exitRow && j === exitCol) {
                cell.classList.add('exit');
            }
            mazeContainer.appendChild(cell);
        }
    }
}

// 移动玩家
function movePlayer(dx, dy) {
    const newRow = playerRow + dy;
    const newCol = playerCol + dx;
    if (newRow >= 0 && newRow < ROWS && newCol >= 0 && newCol < COLS && maze[newRow][newCol] === 0) {
        playerRow = newRow;
        playerCol = newCol;
        drawMaze();
        if (playerRow === exitRow && playerCol === exitCol) {
            alert('恭喜你，成功走出迷宫！');
        }
    }
}

// 键盘事件处理
document.addEventListener('keydown', function (event) {
    switch (event.key) {
        case 'ArrowLeft':
            movePlayer(-1, 0);
            break;
        case 'ArrowRight':
            movePlayer(1, 0);
            break;
        case 'ArrowUp':
            movePlayer(0, -1);
            break;
        case 'ArrowDown':
            movePlayer(0, 1);
            break;
    }
});

// 初始化游戏
initMaze();
drawMaze();